package service.impl;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import model.Passenger;
import model.Role;
import service.PassengerService;
import dao.PassengerDAO;
import dao.RoleDAO;

@Stateless
public class PassengerServiceImpl implements PassengerService {

	@EJB
	private PassengerDAO passengerDAO;
	
	@EJB
	private RoleDAO roleDAO;

	@Override
	public List<Passenger> findAll() {
		return passengerDAO.findAll();
	}

	@Override
	public Passenger findById(Integer id) {
		return passengerDAO.find(id);
	}

	@Override
	public String save(Passenger passenger) {
		if (passengerDAO.findPassengerByLogin(passenger.getLogin()) != null) {
			return "This login already exists";
		}
		if (passengerDAO.findByNameSurname(passenger.getPassengerName(), passenger.getPassengerSurname()) != null) {
			return "These name and surname already exist";
		}
		passengerDAO.save(passenger);
		Role passengerRole = new Role();
		passengerRole.setAuthority("ROLE_USER");
		passengerRole.setPassenger(passengerDAO.find(passenger.getPassengerID()));
		roleDAO.save(passengerRole);
		return "ok";
	}

	@Override
	public String registration(Passenger passenger) {
		passengerDAO.save(passenger);
		Role passengerRole = new Role();
		passengerRole.setAuthority("ROLE_USER");
		passengerRole.setPassenger(passenger);
		roleDAO.save(passengerRole);
		return "ok";
	}

	@Override
	public String delete(Passenger passenger) {
		if (passenger != null) {
			Role role = roleDAO.findByPassenger(passenger);
			if (role != null) {
				roleDAO.delete(role);
			}
			passengerDAO.delete(passenger) ;
			return "ok";
		}
		return "no";
	}

	@Override
	public Passenger findPassengerByLogin(String login) {
		return passengerDAO.findPassengerByLogin(login);
	}

	@Override
	public String update(Passenger passenger) {
		Passenger temp = passengerDAO.find(passenger.getPassengerID());
		if (temp != null) {
			this.delete(temp);
			if (passengerDAO.findPassengerByLogin(passenger.getLogin()) != null) {
				this.registration(temp);
				return "This login already exists";
			}
			if (passengerDAO.findByNameSurname(passenger.getPassengerName(), passenger.getPassengerSurname()) != null) {
				this.registration(temp);
				return "These name and surname already exist";
			}
			passengerDAO.save(passenger);
			Role passengerRole = new Role();
			passengerRole.setAuthority("ROLE_USER");
			passengerRole.setPassenger(passengerDAO.find(passenger.getPassengerID()));
			roleDAO.save(passengerRole);
			return "ok";
		} else {
			return "Please update your page, this passenger doesn't exist!";
		}	
	}
}
